/**
 * 常用方法封装 请求，文件上传等
 **/

const _https = {
	//接口地址
	interfaceUrl: function() {
		return 'https://glht.ckjkj.com'
	},
	toast: function(text, success, duration) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	mapImgurl:function(array) {
	  array.map((v, i, arr) => {
	    arr[i].imgurl = _https.interfaceUrl() + arr[i].imgurl
	    return arr
	  })
	  return array
	},
	formatNumber (n) {
	  n = n.toString()
	  return n[1] ? n : '0' + n
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#58A4E5",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, isForm, postData, method, isDelay, hideLoading) {
		//接口请求
		let loadding = false;
		_https.delayed && uni.hideLoading();
		clearTimeout(_https.delayed);
		_https.delayed = null;
		if (!hideLoading) {
			
			_https.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 700 : 0)
		}

		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			// #endif
			uni.request({
				url: _https.interfaceUrl() + url,
				data: postData,
				header: {
					// 'content-type': 'application/json',
					'content-type':  'application/x-www-form-urlencoded' ,
					'AUTHKEY_TOKEN': _https.getToken()
				},
				method: isForm?'GET':'POST', //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(_https.delayed)
					_https.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}	
					if(res.data.code==1){
						uni.hideLoading()
					}
					if(res.data.code==3){
						setTimeout(()=>{
							uni.removeStorageSync('token');
							uni.navigateTo({
								url: '/pages/login/login'
							})
						},1000)
					}
					uni.hideLoading()
					resolve(res.data)
				},
				fail: (res) => {
					clearTimeout(_https.delayed)
					_https.delayed = null;
					_https.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: _https.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				// file:src,
				header: {
					'AUTHKEY_TOKEN': _https.getToken()
				},
				// formData: {
				// 	'token': _https.getToken()
				// },
				success: function(res) {
					
					uni.hideLoading()
					
					let d = JSON.parse(res.data)
					
					if (d.code == 1) {
						//返回图片地址
						let fullurl = d.data.fullurl;
						resolve(fullurl)
					} else {
						_https.toast(res.msg);
					}
				},
				fail: function(res) {
					reject(res)
					_https.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile,token) {
		//uni.setStorageSync("token", token)
		uni.setStorageSync("mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("token") ? true : false
	},
	isToLogin(){
		if (!_https.isLogin()) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
			return
		}
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !_https.isLogin()) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},
	drawtext(text, maxWidth) {
		let textArr = text.split("");
		let len = textArr.length;
		// 上个节点
		let previousNode = 0;
		// 记录节点宽度
		let nodeWidth = 0;
		// 文本换行数组
		let rowText = [];
		// 如果是字母，侧保存长度
		let letterWidth = 0;
		// 汉字宽度
		let chineseWidth = 21;
		// otherFont宽度
		let otherWidth = 10.5;
		for (let i = 0; i < len; i++) {
			if (/[\u4e00-\u9fa5]|[\uFE30-\uFFA0]/g.test(textArr[i])) {
				if(letterWidth > 0){
					if(nodeWidth + chineseWidth + letterWidth * otherWidth > maxWidth){
						rowText.push({
							type: "text",
							content: text.substring(previousNode, i)
						});
						previousNode = i;
						nodeWidth = chineseWidth;
						letterWidth = 0;
					} else {
						nodeWidth += chineseWidth + letterWidth * otherWidth;
						letterWidth = 0;
					}
				} else {
					if(nodeWidth + chineseWidth > maxWidth){
						rowText.push({
							type: "text",
							content: text.substring(previousNode, i)
						});
						previousNode = i;
						nodeWidth = chineseWidth;
					}else{
						nodeWidth += chineseWidth;
					}
				}
			} else {
				if(/\n/g.test(textArr[i])){
					rowText.push({
						type: "break",
						content: text.substring(previousNode, i)
					});
					previousNode = i + 1;
					nodeWidth = 0;
					letterWidth = 0;
				}else if(textArr[i] == "\\" && textArr[i + 1] == "n"){
					rowText.push({
						type: "break",
						content: text.substring(previousNode, i)
					});
					previousNode = i + 2;
					nodeWidth = 0;
					letterWidth = 0;
				}else if(/[a-zA-Z0-9]/g.test(textArr[i])){
					letterWidth += 1;
					if(nodeWidth + letterWidth * otherWidth > maxWidth){
						rowText.push({
							type: "text",
							content: text.substring(previousNode, i + 1 - letterWidth)
						});
						previousNode = i + 1 - letterWidth;
						nodeWidth = letterWidth * otherWidth;
						letterWidth = 0;
					}
				} else{
					if(nodeWidth + otherWidth > maxWidth){
						rowText.push({
							type: "text",
							content: text.substring(previousNode, i)
						});
						previousNode = i;
						nodeWidth = otherWidth;
					}else{
						nodeWidth += otherWidth;
					}
				}
			}
		}
		if (previousNode < len) {
			rowText.push({
				type: "text",
				content: text.substring(previousNode, len)
			});
		}
		return rowText;
	}
}
// let postData = {}
// this.$https.request('/apis/article/getArticleList','GET',postData).then((res)=>{
// 		console.log(res);
// }).catch((res)=>{
// 		console.log(res);
// });

export default _https